package com.cctv.kvtest

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Button
import io.fastkv.FastKV
import io.fastkv.FastKVConfig
import java.util.concurrent.ThreadPoolExecutor

class MainActivity : AppCompatActivity() {
    private lateinit var tv: Button
    private lateinit var td: ThreadPoolExecutor
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        td = MyThreadPool.getInstance(object : MyThreadPool.Callback {
            override fun before(t: Thread?, r: Runnable?) {
                DebugLog.e("开始前${t?.name}");
            }

            override fun after(r: Runnable?, t: Throwable?) {
                DebugLog.e("之后");
            }

            override fun terminat() {
                DebugLog.e("shutdown");
            }

        })
        FastKVConfig.setExecutor(td)
        tv = findViewById<Button>(R.id.times)
        val kv =
            FastKV.Builder(applicationContext.getDir("fastkv", Context.MODE_PRIVATE).absolutePath,
                "common_store").build()
        //启动一次就加1
        var t = kv.getInt("launch_count") + 1
        kv.putInt("launch_count", t)

        DebugLog.e("$t");
        tv.text = "$t"
        tv.setOnClickListener {
            //手动add
//            tv.text = "${++t}"
//            kv.putInt("launch_count", t)
//            DebugLog.e("$t");
            td.execute {
                for (i in 0 until 5) {
                    Thread.sleep(5000)
                    /*tv.text = */"${++t}"
                    val msg = Message()
                    msg.arg1 = t
                    hand.sendMessage(msg)
                    kv.putInt("launch_count", t)
                    DebugLog.e("$t  ${Thread.currentThread().name}");
                    DebugLog.e(
                        "${td.activeCount}+${td.completedTaskCount}=${td.taskCount}  ${td.poolSize}/${td.largestPoolSize}");
                }
            }
        }
    }

    private val hand = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            tv.text = "${msg.arg1}"
        }
    }

    override fun onStop() {
        super.onStop()
        if(!td.isTerminated){
//            td.shutdown()
//            td.awaitTermination()
            td.shutdownNow()
        }
    }
    override fun onDestroy() {
        super.onDestroy()

    }
}